package org.lemon.cla.exception.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.lemon.cla.dto.response.ResponseResult; // 确保导入你的 ResponseResult
import org.lemon.cla.enums.HttpStatusEnum; // 确保导入你的 HttpStatusEnum
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException; // 导入 AccessDeniedException
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义访问拒绝处理器
 * 当认证用户尝试访问受保护资源，但没有足够权限时，由 AccessDeniedException 触发。
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper;

    public CustomAccessDeniedHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {

        // 设置响应状态码为 403 Forbidden (无权限)
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        // 设置响应内容类型为 JSON
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        // 构建统一的错误响应体
        ResponseResult<Void> result = ResponseResult.fail(
                HttpStatusEnum.FORBIDDEN.getCode(), // 403 对应的枚举代码
                "您没有足够的权限访问此资源。" // 具体错误信息
        );

        // 将结果写入响应体
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}